package com.ablife.limiter.algorithm;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import redis.clients.jedis.Jedis;
import redis.clients.jedis.JedisPool;

@Service
public class CountRateLimiter implements Limiter {
    private static final Logger logger = LoggerFactory.getLogger(CountRateLimiter.class);
    @Autowired
    private JedisPool jedisPool;

    public CountRateLimiter() {
    }

    /**
     * @author hzh
     * description:
     * @param channel 渠道：BANK_INSURANCE->银保、WECHAT->微信
     * @param tradeCode 限流交易名：EDORAPPLY_CT、EDORCALC_CT
     * @param type 限流类型：1查询、2计数
     */
    public boolean doLimit(String channel, String tradeCode, String type) {
        channel = channel.toUpperCase();
        tradeCode = tradeCode.toUpperCase();

        try {
            Jedis jedis = this.jedisPool.getResource();
            Throwable var5 = null;

            boolean var7;
            try {
                // 是否开启限流
                if (!"1".equals(jedis.get("MAINSWITCH"))) {
                    // 未开启，放行
                    return true;
                }

                // 查询是否存在当前限流交易
                String key = "TRADECONFIG|" + tradeCode + "|" + channel;
                if (!jedis.exists(key)) {
                    // 不存在，放行
                    return true;
                }

                // 类型，1查询，2计数
                if ("1".equals(type)) {
                    return this.doQuery(key);
                }

                var7 = !"2".equals(type) || this.doCount(key);
            } catch (Throwable var20) {
                var5 = var20;
                throw var20;
            } finally {
                if (jedis != null) {
                    if (var5 != null) {
                        try {
                            jedis.close();
                        } catch (Throwable var19) {
                            var5.addSuppressed(var19);
                        }
                    } else {
                        jedis.close();
                    }
                }

            }

            return var7;
        } catch (Exception var22) {
            return true;
        }
    }

    private boolean doQuery(String key) {
        try {
            Jedis jedis = this.jedisPool.getResource();
            Throwable var3 = null;

            boolean var7;
            try {
                // 获取当前限流配置的计数器
                String group = jedis.get(key).toUpperCase();
                int count = 0;
                String TRADECOUNT_KEY = "TRADECOUNT|" + group;
                if (jedis.exists(TRADECOUNT_KEY)) {
                    // 计数器已经计数的值
                    count = Integer.parseInt(jedis.get("TRADECOUNT|" + group));
                }
                // 获取当前组里的上限值sum
                String configGroup = jedis.get("CONFIG|" + group);
                configGroup = configGroup.split("\\|")[1];
                int sum = Integer.parseInt(configGroup);
                logger.info("type1----key:" + key + "----config_group:" + group + "--count:" + count + "--limit:" + sum);
                // 判断当前的count是否小于上限sum
                var7 = count < sum;
            } catch (Throwable var17) {
                var3 = var17;
                throw var17;
            } finally {
                if (jedis != null) {
                    if (var3 != null) {
                        try {
                            jedis.close();
                        } catch (Throwable var16) {
                            var3.addSuppressed(var16);
                        }
                    } else {
                        jedis.close();
                    }
                }

            }

            return var7;
        } catch (Exception var19) {
            return true;
        }
    }

    private boolean doCount(String key) {
        try {
            Jedis jedis = this.jedisPool.getResource();
            Throwable var3 = null;

            boolean var23;
            try {
                String group = jedis.get(key).toUpperCase();
                // 当前key的val自增加1
                Long count = jedis.incr("TRADECOUNT|" + group);
                // 获取上限值
                Long sum = Long.valueOf(jedis.get("CONFIG|" + group).split("\\|")[1]);
                logger.info("type2----key:" + key + "----config_group:" + group + "--count:" + count + "--limit:" + sum);
                // 判断是否超出上限
                if (count > sum) {
                    return false;
                }

                String configGroup = jedis.get("CONFIG|" + group);
                if (count == 1L) {
                    long timeout = Long.parseLong(configGroup.split("\\|")[3]);
                    // 重置当前key的过期时间,使用pexpire设置时间单位为毫秒
                    jedis.pexpire("TRADECOUNT|" + group, timeout);
                }

                var23 = true;
            } catch (Throwable var19) {
                var3 = var19;
                throw var19;
            } finally {
                if (jedis != null) {
                    if (var3 != null) {
                        try {
                            jedis.close();
                        } catch (Throwable var18) {
                            var3.addSuppressed(var18);
                        }
                    } else {
                        jedis.close();
                    }
                }

            }

            return var23;
        } catch (Exception var21) {
            return true;
        }
    }
}
